<?php
/**
 * Created by PhpStorm.
 * User: ysongyang
 * Date: 2016/6/6
 * Time: 14:55
 */
namespace Admin\Controller;
class AccessController extends CommonController{
    function _initialize()
    {
        parent::_initialize();
        $this->roles = M('role');
        $this->nodes = M('node');
        $this->users = D('User');
        $this->_role_user = M('role_user');
    }


    // 用户列表首页
    public function user()
    {
        // 关联模型
        $user =$this->users->field('password', true)
            ->relation('role', true)
            ->select();
        $this->user = $user;
        $this->display();
    }



    // 添加用户表单处理
    public function addUser()
    {
        if (IS_POST){
            $username = I('username');
            $password = md5(C('AUTH_CODE') . md5(I('password')));
            $username_is = $this->users->where(array(
                'username' => $username
            ))->select();
            if (! $username_is) {
                $role = array();
                $data = array(
                    'username' => $username,
                    'password' => $password,
                    'logintime' => time(),
                    'loginip' => get_client_ip()
                );
                if ($uid = $this->users->add($data)) {
                    foreach ($_POST['role_id'] as $v) {
                        $role[] = array(
                            'role_id' => $v,
                            'user_id' => $uid
                        );
                    }
                    $this->_role_user ->addAll($role);
                    $this->success('添加成功！', U(MODULE_NAME.'/Access/user'));
                }
            } else {
                $this->error('用户名已存在！');
            }
        }else{
            $this->role = $this->roles->select(); // 将角色数组传值
            $this->display();
        }
    }

    /**
     * 修改用户方法
     */
    public function editUser()
    {
        if (IS_POST) {

            $id = I('uid', '', 'intval');
            $username = I('username');
            $password = $_POST['password'] ? md5(C('AUTH_CODE') . md5(I('password'))) : $_POST['password'];
            $lock = I('lock','',intval);
            $logintime = time();
            $loginip = get_client_ip();
            // 判断用户名修改后是否会出现重复
            if (username_is($id, $username)) {
                $this->error('你要修改的用户名已存在，请重新修改！');
            } else {
                if ($password) { // 如果密码不为空，代表用户修改密码，为空则不修改密码
                    $this->users->where(array('id' => $id))->save(array(
                        'username' => $username,
                        'password' => $password,
                        'lock' =>$lock,
                        'logintime' => $logintime,
                        'loginip' => $loginip
                    ));
                    // 根据UID 先清空权限配置标的权限
                    $this->_role_user ->where(array(
                        'user_id' => $id
                    ))->delete();
                    foreach ($_POST['role_id'] as $v) {
                        $role[] = array(
                            'role_id' => $v,
                            'user_id' => $id
                        );
                    }
                    $this->_role_user->addAll($role);
                    $this->success('修改成功！', U(MODULE_NAME . '/Access/user'));
                } else {
                    $this->users->where(array('id' => $id))->save(array(
                        'username' => $username,
                        'lock' =>$lock,
                        'logintime' => $logintime,
                        'loginip' => $loginip
                    ));
                    // 根据UID 先清空权限配置标的权限
                    $this->_role_user ->where(array(
                        'user_id' => $id
                    ))->delete();
                    foreach ($_POST['role_id'] as $v) {
                        $role[] = array(
                            'role_id' => $v,
                            'user_id' => $id
                        );
                    }
                    $this->_role_user ->addAll($role);
                    $this->success('修改成功！', U(MODULE_NAME . '/Access/user'));
                }
            }
        }else{
            $id = I('id', 0, 'intval');
            $user = $this->users->where(array('id' => $id))->find();
            $role = user_role($id);
            $this->user = $user;
            $this->role = $role;
            $this->display();
        }
    }



    /**
     * 删除用户方法
     */
    public function deleteUser()
    {
        $uid = I('id', 0, 'intval'); // 获取删除节点ID
        if ($this->users->where(array('id' => $uid))->delete()) {
            // 删除用户后，清空权限表的数据
            $this->_role_user ->where(array('user_id' => $uid))->delete();
            $data['status'] = 1;
            $data['info'] = '删除成功！';
        } else{
            $data['status'] = 0;
            $data['info'] = '删除失败！';
        }
        $this->ajaxReturn($data);
    }

    /**
     * 角色列表
     */
    public function role(){

        $count = $this->roles -> count();
        $page = new \Think\Page($count, 10);
        // 实例化分页类 条数，分页数
        $limit = $page -> firstRow . ',' . $page -> listRows;

        $this->role = $this->roles->limit($limit)->order('sort asc') ->select();
        $this -> page = $page -> show();
        $this->display();
    }


    //添加角色
    public function addRole()
    {
        if (IS_POST){
            $name = I('name');
            $name_IS = $this->roles->where(array('name' => $name))->find();
            // 如果添加的角色名称不存在
            if (!$name_IS) {
                if ($this->roles->add($_POST))
                    $this->success('添加角色成功！', U(MODULE_NAME . '/Access/role'));
            } else {
                $this->error('你添加的角色名称已存在！');
            }
        }else{
            $this->display();
        }
    }



    // 修改角色及角色修改处理方法
    public function editRole()
    {
        if (IS_POST){
            $id = I('id', 0, 'intval');
            $name = I('name');
            $remark = I('remark');
            $status = I('status', 0, 'intval');
            if (rolename_is($id, $name)) {
                $this->error('角色名称已存在！');
            } else {
                if ($this->roles->where(array('id' => $id))->save(array(
                    'name' => $name,
                    'remark' => $remark,
                    'status' => $status
                ))) {
                    $this->success('修改成功！', U(MODULE_NAME . '/Access/role'));
                } else {
                    $this->error('修改失败！');
                }
            }
        }else{
            $id = I('id', 0, 'intval');
            $role = $this->roles->where(array('id' => $id))->find();
            $this->role = $role;
            $this->display();
        }


    }


    //删除节点方法处理
    public function deleteRole(){
        $id=I('id',0,'intval');//获取删除节点ID
        if($this->roles->where(array('id'=>$id))->delete())
        {
            $data['status'] = 1;
            $data['info'] = '删除成功！';
        } else{
            $data['status'] = 0;
            $data['info'] = '删除失败！';
        }
        $this->ajaxReturn($data);
    }


    // 节点列表
    public function node()
    {
        $field = array('id','name','title','pid','sort');
        $node = $this->nodes->field($field)->select();
        $this->node = node_merge($node);
        $this->display();
    }

    // 添加节点及修改节点方法
    public function addNode()
    {

        if (IS_POST){
            $name = I('name'); // 获取输入的名称 判断是否存在
            $pid = I('pid'); // 获取当前添加的节点pid
            $type = I('type');
            $nodeName_is = $this->nodes->where(array('name' => $name,'pid' => $pid))->find(); // 查找数据库里是否存在这条信息
            if (! $nodeName_is) {
                if ($this->nodes->add($_POST)) {
                    $this->success('添加'.$type.'成功！', U(MODULE_NAME . '/Access/node'));
                } else {
                    $this->error('添加'.$type.'失败，请稍后再试！');
                }
            } else {
                $this->error('操作失败，你添加的' . $type . '名称已存在！');
            }
        }else{
            $this->pid = I('pid', 0, 'intval');
            $this->level = I('level', 1, 'intval');
            switch ($this->level) {
                case 1:
                    $this->type = "模块";
                    $this->typename = "模块名称即为分组文件夹名称";
                    break;
                case 2:
                    $this->type = "控制器";
                    $this->typename = "AdminAction.class.php / 既填写Admin";
                    break;
                case 3:
                    $this->type = "方法";
                    $this->typename = "填写控制器中的方法名称，请区分大小写";
                    break;
            }
            $this->display();
        }
    }
    // 修改节点
    public function editNode()
    {
        if(IS_POST){
            $id = I('id', 0, 'intval'); // 获取节点ID
            $this->nodes->where(array('id'=>$id))->save($_POST);
            $this->success('修改成功',U(MODULE_NAME . '/Access/node'));
            /* if($res){
                  $data['status'] = 1;
                  $data['info'] = '修改成功！';
              }else{
                  $data['status'] = 0;
                  $data['info'] = '修改失败，请稍后再试！';
              }
             $this->ajaxReturn($data);*/
        }else{
            $id = I('id', 0, 'intval'); // 获得修改的节点id
            $node = $this->nodes->where(array('id' => $id))->find();
            switch ($node['level']) {
                case 1:
                    $this->type = "模块";
                    $this->typename = "应用名称即为分组文件夹名称";
                    break;
                case 2:
                    $this->type = "控制器";
                    $this->typename = "AdminAction.class.php / 既填写Admin";
                    break;
                case 3:
                    $this->type = "方法";
                    $this->typename = "填写控制器中的方法名称，请区分大小写";
                    break;
            }
            $this->assign('node',$node);
            $this->display();
        }
    }
    //删除节点方法处理
    public function deleteNode(){
        $id=I('id',0,'intval');//获取删除节点ID
        $count=$this->nodes->where(array('pid'=>$id))->count();
        if($count){
            $data['status'] = 0;
            $data['info'] = '请先删除子类的内容！';
        }else{
            if($this->nodes->where(array('id'=>$id))->delete())
            {
                $data['status'] = 1;
                $data['info'] = '删除成功！';
            } else{
                $data['status'] = 0;
                $data['info'] = '删除失败！';
            }
        }
        $this->ajaxReturn($data);
    }


    //异步更新排序
    public function changenode(){
        $res=$this->nodes->where(array('id'=>$_POST['id']))->save(array('sort'=>$_POST['sort']));
        /* echo M()->getLastSql();
         die;*/
        if($res){
            $data =array('status'=>1,'info'=>'排序更新成功！');
        }else{
            $data = array('status'=>0,'info'=>'排序更新失败，请稍后再试！');
        }
        $this->ajaxReturn($data);
    }



    //异步更新排序
    public function change(){
        $res=$this->roles->where(array('id'=>$_POST['id']))->save(array('sort'=>$_POST['sort']));
        /* echo M()->getLastSql();
         die;*/
        if($res){
            $data =array('status'=>1,'info'=>'排序更新成功！');
        }else{
            $data = array('status'=>0,'info'=>'排序更新失败，请稍后再试！');
        }
        $this->ajaxReturn($data);
    }


    // 配置权限方法
    public function access()
    {
        $rid = I('rid', 0, 'intval'); // 获取角色ID
        $field = array(
            'id',
            'name',
            'title',
            'pid'
        );
        // 节点
        $node = $this->nodes->order('sort')
            ->field($field)
            ->select();
        // 权限
        $access = M('access')->where(array(
            'role_id' => $rid
        ))->getField('node_id', true);

        $this->node = node_merge($node, $access);

        $this->rid = $rid;
        $this->display();
    }

    // 配置权限修改方法
    public function setAccess()
    {
        $rid = I('rid', 0, 'intval'); // 获取角色ID
        $db = M('access');

        // 根据$rid清空原来权限信息
        $db->where(array(
            'role_id' => $rid
        ))->delete();
        $data = array();
        // 组合新权限
        foreach ($_POST['access'] as $v) {
            $tmp = explode('_', $v);
            $data[] = array(
                'role_id' => $rid,
                'node_id' => $tmp[0],
                'level' => $tmp[1]
            );
        }
        // 插入权限
        if ($db->addAll($data)) {
            $this->success('配置权限成功', U(MODULE_NAME . '/Access/role'));
        } else {
            $this->error('配置权限失败');
        }
    }

}